<?php
include_once 'application/application.php';

function fatalErrorShutdownHandler(){
   $last_error = error_get_last();
        if (in_array($last_error['type'], array(E_ERROR,E_COMPILE_ERROR))) {
         // fatal error
         ?>
<div class="well well-small span7" style="border-color: red; color:red;">
    <?php echo $last_error['message']." ({$last_error['type']})"; ?>
</div>
         <?php
      }
}


register_shutdown_function('fatalErrorShutdownHandler', E_ALL);
/** /
error_reporting(0);
/**/

class VTABLES {
    public $tableviews    = 'views_object_list_dev';
    public $tableviews_PRODUCTION    = 'views_object_list';
    public $tablevgroup   = 'views_group_list';
    public $tablecnc      = 'views_conception_list';
    public $tablefloors   = 'views_floors_list';
    public $tablesen      = 'views_floors_sensors_list';
}


class FLDS_ {

    public $id;
    public $floor_id;
    public $tbl;
    public $sen;
    public $time_min;
    public $time_max;
    public $time_shift;
    public $whatsum;
    public $use_timelimit;

    public function getFields() {
        $vars = get_class_vars(get_class());
        return is_array($vars)? array_keys($vars) : array();
    }


    public function saveToDB() {
        $J = new JSON();
        $vt = new VTABLES();
        $id = $this->id? $this->id : 'NULL';
        $this->use_timelimit = $this->use_timelimit? 1 : 0;
        if (!$this->time_shift) $this->time_shift = 0;
        $sen = mysql_escape_string($this->sen);

        $q = "
            INSERT INTO `{$vt->tablesen}`  (
                        id,
                        floor_id,
                        tbl,
                        sen,
                        use_timelimit,
                        time_min,
                        time_max,
                        time_shift,
                        whatsum
                        )
            VALUES (
                        {$id},
                        {$this->floor_id},
                        '{$this->tbl}',
                        '{$sen}',
                        {$this->use_timelimit},
                        TIME('{$this->time_min}'),
                        TIME('{$this->time_max}'),
                        {$this->time_shift},
                        '{$this->whatsum}'
                    )
        ";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка записи данных ('.DB::$mysqli->error.')');
        }

        $J->insertedId = DB::$mysqli->insert_id;
        $this->id = $J->insertedId;

        $th = (array)$this;

        if (class_exists('Log')) Log::Save(OPERATION::CREATE_VWFLDS, $th);
        return $J;
    }
}







class FL {
    public $id = 'NULL';
    public $name;
    public $view_id;
    public $view_order;

    private $dss = array();

    public function getFields() {
        $vars = get_class_vars(get_class());
        return is_array($vars)? array_keys($vars) : array();
    }

    public function addDs($ds) {
        if ($ds instanceof FLDS_) {
            $ds->floor_id = $this->id;
            $this->dss[] = $ds;
        }
    }

    public function getDs() {return $this->dss;}

    public function saveToDB() {
        $J = new JSON();
        $vt = new VTABLES();
        $q = "
            INSERT INTO `{$vt->tablefloors}`
                        (id,          name,                view_id,              view_order          )
            VALUES      ({$this->id}, '".  mysql_escape_string($this->name)."',     {$this->view_id},     {$this->view_order} )
        ";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка записи данных <!--('.DB::$mysqli->error.')-->');
        }

        $J->insertedId = DB::$mysqli->insert_id;
        $this->id = $J->insertedId;

        $th = (array)$this;

        if (class_exists('Log')) Log::Save(OPERATION::CREATE_VWFLOOR, $th);
        return $J;
    }
}






class Page_converter {
    const ACTION    = 'CONVERT_LOADERS';
    const BACKUP_VWTABLE = 'BACKUP_VWTABLE';

    private $tableviews = 'views_object_list_dev';
    private $tablevgroup = 'views_group_list';
    private $tablecnc = 'views_conception_list';
    private $tablefloors = 'views_floors_list';
    private $tablesen = 'views_floors_sensors_list';



    public $action;
    public $error;
    public $resultHtml = '';



    public function __construct() {
        $this->action = Arr::getValue($_POST, 'action', false);

        DB::connect();
        if (!DB::state()) {
            $this->error = DB::getError();
        }
    }


    public function __destruct() {

    }



    function fillData () {
        if (!ConceptionsCollection::Init())
            $this->error = 'Проблемы со списком концепций';
        $params = array();

        $id = Arr::getValue($_POST, 'id', 0);

        $alles = array(
            'views' => getAllViews_(),
            'cities' => getAllCities(),
            'vgroups' => getAllViewsGroups(),
            'conceptions' => ConceptionsCollection::allRowsById(),
            'types' => getObjTypes(),
            'btypes' => getBuildTypes(),
            'datatypes' => getDataTypes()
        );

        if ($id) {
            $params = Arr::getValue($alles['views'], $id, false);
            if (!$params) {
                $this->error = 'Отображение не существует';
                return $alles;
            }

            $params['view_mode'] = 1; // !!!!!!

        }

        foreach ($alles as $key => $val) {
            $params[$key] = $val;
        }

        return $params;
    }


    function fieldRead(&$J) {
        $params = array();

        $params['id'] = Arr::getValue($_POST, 'vw_id', 0);

        $params['action']           = $J->readVar('action');
        $params['vw_id']            = (int)$J->readVar('vw_id',0);
        $params['view_mode']        = (int)($J->readVar('view_mode', 1));
        $params['obj_name']         = mysql_escape_string($J->readVar('obj_name'));
        $params['obj_type']         = (int)($J->readVar('obj_type'));
        $params['build_type']       = (int)($J->readVar('build_type',0));
        $params['parent_id']        = (int)($J->readVar('parent_id'));
        $params['group']            = (int)($J->readVar('group'));
        $params['obj_short_name']   = mysql_escape_string($J->readVar('obj_short_name'));
        $params['city_id']          = (int)($J->readVar('city_id'));
        $params['address']          = mysql_escape_string($J->readVar('address'));
        $params['lattitude']        = mysql_escape_string($J->readVar('lattitude',0));
        $params['longitude']        = mysql_escape_string($J->readVar('longitude',0));
        $params['area']             = (int)($J->readVar('area',0));
        $params['conception']       = (int)($J->readVar('conception'));
        $params['dev']              = (int)($J->readVar('dev',0));
        $params['viewable']         = (int)($J->readVar('viewable',1));
        $params['is_new']           = (int)($J->readVar('is_new',0));
        $params['def_floor']        = (int)($J->readVar('def_floor',0));

        return $params;
    }





    public function itemAdd($params = null) {

        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');


        $vt = new VTABLES();

        $params = array_merge(array(
            'id'                => 'NULL',
            'obj_name'          => '?',
            'obj_short_name'    => '',
            'group'             => 0,
            'city_id'           => 0,
            'obj_type'          => 0,
            'build_type'        => 0,
            'def_floor'         => 0,
            'view_mode'         => 1,
            'parent_id'         => 0,
            'history_obj_id'    => 0,
            'view_order'        => 0,
            'conception'        => 0,
            'pcvideo'           => '',
            'ivideo'            => '',
            'area'              => 0,
            'address'           => '',
            'lattitude'         => 0,
            'longitude'         => 0,
            'is_new'            => 1,
            'dev'               => 1,
            'viewable'          => 0,
            'logo'              => ''
        ), $params);


        $q = "INSERT INTO `{$vt->tableviews}`
                (
                    `id`,
                    `obj_name`,
                    `obj_short_name`,
                    `group`,
                    `city_id`,
                    `obj_type`,
                    `build_type`,
                    `def_floor`,
                    `view_mode`,
                    `parent_id`,
                    `history_obj_id`,
                    `view_order`,
                    `conception`,
                    `pcvideo`,
                    `ivideo`,
                    `area`,
                    `address`,
                    `lattitude`,
                    `longitude`,
                    `is_new`,
                    `dev`,
                    `viewable`,
                    `logo`
                )
                VALUES
                (
                    '{$params['id']}',
                    '{$params['obj_name']}',
                    '{$params['obj_short_name']}',
                    '{$params['group']}',
                    '{$params['city_id']}',
                    '{$params['obj_type']}',
                    '{$params['build_type']}',
                    '{$params['def_floor']}',
                    '{$params['view_mode']}',
                    '{$params['parent_id']}',
                    '{$params['history_obj_id']}',
                    '{$params['view_order']}',
                    '{$params['conception']}',
                    '{$params['pcvideo']}',
                    '{$params['ivideo']}',
                    '{$params['area']}',
                    '{$params['address']}',
                    '{$params['lattitude']}',
                    '{$params['longitude']}',
                    '{$params['is_new']}',
                    '{$params['dev']}',
                    '{$params['viewable']}',
                    '{$params['logo']}'
                )";



        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при сохранении данных ('.DB::$mysqli->error.')');
            return $J;
        }

        $J->insertedId = DB::$mysqli->insert_id;

        $params['id'] = $J->insertedId;
        if (class_exists('Log')) Log::Save(OPERATION::CREATE_VIEW, $params);

        return $J;

    }



    public function itemAddFromHistoryObject() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $id        = (int)$J->readVar('ho_id',0);
        //$params['vw_id']   = (int)$J->readVar('vw_id',0);


        $q = "  SELECT * FROM `admin_conn_history`
                WHERE id = {$id}
                LIMIT 0,1";

        $res = DB::query($q);

        if (!$res || !DB::state()) return $J->error('Ошибка при работе с базой данных <!--'.DB::getError().'-->');

        $row = mysqli_fetch_array($res, MYSQLI_ASSOC);
        if (!$row) return $J->error('Запись не найдена');

        $params = array(
            'obj_name'          => $row['name'],
            'obj_type'          => $row['obj_type'],
            'build_type'        => $row['build_type'],
            'parent_id'         => 0,
            'group'             => 0,
            'obj_short_name'    => '',
            'city_id'           => 0,
            'address'           => $row['address'],
            'lattitude'         => 0,
            'longitude'         => 0,
            'area'              => 0,
            'conception'        => 0,
            'dev'               => 1,
            'viewable'          => 0,
            'is_new'            => 1
        );


        $J1 = $this->itemAdd($params);
        if (!$J1->getState()) return $J->error($J1->getErrorString ());

        $J->vwId = $J1->insertedId;;
        $J->vwName = $row['name'];


        $q = "UPDATE `admin_conn_history`
              SET view_id = $J->vwId
              WHERE id = {$id}";
        $res = DB::query($q);
        if (!$res || !DB::state()) return $J->error('Ошибка при работе с базой данных <!--'.DB::getError().'-->');



        $J2 = $this->floorCreate($J->vwId);
        if (!$J2->getState()) return $J;//->error ($J2->getErrorString ());
        else $J->flId = $J2->insertedId;


        $J3 = $this->createFLDS(array(
            'floor_id'      => $J->flId,
            'tbl'           => $row['tbl'],
            'sen'           => $row['sen'],
            'time_min'      => 0,
            'time_max'      => 0,
            'time_shift'    => 0,
            'whatsum'       => '',
            'use_timelimit' => 0
        )) ;
        if (!$J3->getState()) return $J;//->error ($J3->getErrorString ());
        else $J->fldsId = $J3->insertedId;

        return $J;
    }














    public function itemUpdate() {

        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = $this->fieldRead($J);
        $wrongFields = $this->checkFields($params);



        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }

        $all = getAllViews_(); // array('byId'=>array(), 'byFio'=>array());
        if (!DB::$lastReqState) return $J->error('Не удалось получить список отображений <!--'.DB::getError().'-->');

        $old_val = Arr::getValue($all, $params['vw_id'], false);
        if (!is_array($old_val)) return $J->error('Отображение не существует');

        $vt = new VTABLES();


        $q = "UPDATE `{$vt->tableviews}`
              SET
                    `obj_name` = '{$params['obj_name']}',
                    `obj_type` = '{$params['obj_type']}',
                    `build_type` = '{$params['build_type']}',
                    `parent_id` = '{$params['parent_id']}',
                    `group` = '{$params['group']}',
                    `obj_short_name` = '{$params['obj_short_name']}',
                    `city_id` = '{$params['city_id']}',
                    `address` = '{$params['address']}',
                    `lattitude` = '{$params['lattitude']}',
                    `longitude` = '{$params['longitude']}',
                    `area` = '{$params['area']}',
                    `conception` = '{$params['conception']}',
                    `dev` = '{$params['dev']}',
                    `viewable` = '{$params['viewable']}',
                    `is_new` = '{$params['is_new']}'
              WHERE id = {$params['vw_id']}";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
        }

        $J->insertedId = $params['vw_id'];//DB::$mysqli->insert_id;
        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_VIEW, array('old_value'=>$old_val, 'new_value'=>$params, 'id'=>$params['vw_id']));

        $params = $this->addVisualParams($params);

        //$J->parent_name = Arr::getValue($params, 'parent_name', '');
        //$J->obj_type_text = Arr::getValue($params, 'obj_type_text', '');
        $J->city_name = Arr::getValue($params, 'city_name', '');
        $J->cnc_name = Arr::getValue($params, 'cnc_name', '');

        return $J;


    }


    public function getFloors() {
        $J = new JSON();
        $params['vw_id'] = (int)$J->readVar('vw_id',0);
        $J->readVar('action');
        if (!Auth::isLogged()) return $J->error('not_logged');

        $floors = getFloorsByViewId($params['vw_id']);
        $J->floors = $floors['byOrder'];
        if (!DB::$lastReqState) return $J->error('Не удалось получить список срезов данных <!--'.DB::getError().'-->');
        if (!$params['vw_id']) return $J;

        $vt = new VTABLES();

        $q = "SELECT * FROM `{$vt->tableviews}` WHERE id = {$params['vw_id']}";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка чтения данных <!--('.DB::$mysqli->error.')-->');
        }
        $row = $res->fetch_assoc();
        if (is_array($row)) $J->view = $row;

        return $J;
    }


    public function floorCreate($vw_id=null) {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = array();
        $params['view_id'] = (int)$J->readVar('vw_id',0);
        $params['view_id'] = (is_null($vw_id))?  (int)$J->readVar('vw_id',0) : $vw_id;
        $J->readVar('action');

        $all = getAllViews_();
        if (!DB::$lastReqState) return $J->error('Не удалось получить список отображений <!--'.DB::getError().'-->');
        if (!is_array(Arr::getValue($all, $params['view_id'], false))) return $J->error('Отображение не найдено');

        $floors = getFloorsByViewId($params['view_id']);
        $maxOrder = 0;
        if (is_array($floors['byOrder'])) {
            $c = count($floors['byOrder']);
            if ($c) {
                $m = Arr::getValue($floors['byOrder'],$c-1,false);
                if ($m) $maxOrder = $m->view_order;
            }
        }

        $params['name'] = 'new';
        $params['view_order'] = $maxOrder+1;
        $params['picture'] = '';

        $q = "
            INSERT INTO `{$this->tablefloors}`
                        (id,   name,                view_id,              view_order)
            VALUES      (NULL, '{$params['name']}', {$params['view_id']}, {$params['view_order']} )
        ";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка записи данных <!--('.DB::$mysqli->error.')-->');
        }
        $J->insertedId = DB::$mysqli->insert_id;
        $params['id'] = $J->insertedId;
        $J->floor = $params;

        if (class_exists('Log')) Log::Save(OPERATION::CREATE_VWFLOOR, $params);
        return $J;
    }



    public function floorUpdateName() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = array();
        $params['id']       = (int)$J->readVar('id',0);
        $params['vw_id'] = (int)$J->readVar('vw_id',0);
        $params['name']     = mysql_escape_string($J->readVar('name'));

        $floors = getFloorsByViewId($params['vw_id']);
        $fl = Arr::getValue($floors['byId'], $params['id'], false);
        if (!$fl) return $J->error('Срез данных не найден');

        $q = "UPDATE `{$this->tablefloors}`
              SET name = '{$params['name']}'
              WHERE id = {$params['id']}";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
        }

        $J->insertedId = DB::$mysqli->insert_id;
        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_VWFLOOR_NAME, array('old_value'=>$fl->name, 'new_value'=>$params['name'], 'id'=>$params['id']));

        $fl->name = $params['name'];
        $J->floor = $fl;

        return $J;
    }



    public function setDefaultFloor() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = array();
        $params['id']       = (int)$J->readVar('id',0);
        $params['vw_id'] = (int)$J->readVar('vw_id',0);


        $all = getAllViews_();
        if (!DB::$lastReqState) return $J->error('Не удалось получить список отображений <!--'.DB::getError().'-->');
        $oldval = Arr::getValue($all, $params['vw_id'], false);
        if (!is_array($oldval)) return $J->error('Отображение не найдено');

        $floors = getFloorsByViewId($params['vw_id']);
        $fl = Arr::getValue($floors['byId'], $params['id'], false);
        if (!$fl) return $J->error('Срез данных не найден');
        $vt = new VTABLES();

        $q = "UPDATE `{$vt->tableviews}`
              SET def_floor = '{$params['id']}'
              WHERE id = {$params['vw_id']}";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
        }

        $J->result = true;
        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_VWFLOOR_DEF, array('old_value'=>$oldval['def_floor'], 'new_value'=>$params['id'], 'id'=>$params['vw_id']));

        return $J;
    }


    public function deleteFloor() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = array();
        $params['id']       = (int)$J->readVar('id',0);
        $params['vw_id'] = (int)$J->readVar('vw_id',0);

        $all = getAllViews_();
        if (!DB::$lastReqState) return $J->error('Не удалось получить список отображений <!--'.DB::getError().'-->');
        $vw = Arr::getValue($all, $params['vw_id'], false);
        if (!is_array($vw)) return $J->error('Отображение не найдено');

        $floors = getFloorsByViewId($params['vw_id']);
        $fl = Arr::getValue($floors['byId'], $params['id'], false);
        if (!$fl) return $J->error('Срез данных не найден');

        // transaction start
        DB::$mysqli->autocommit(FALSE);

        $q = "DELETE FROM `{$this->tablefloors}` WHERE id = {$params['id']}";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
        }

        if ($J->getState()) {
            $q = "DELETE FROM `{$this->tablesen}` WHERE floor_id = {$params['id']}";
            $res = DB::query($q);
            if (!$res || !DB::state()) {
                $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
            }
        }

        $vt = new VTABLES();

        if ($J->getState() && $vw['def_floor'] == $params['id']) {
            $q = "UPDATE `{$vt->tableviews}` SET def_floor = 0 WHERE id = {$vw['id']}";
            $res = DB::query($q);
            if (!$res || !DB::state()) {
                $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
            }
        }

        if (!$J->getState()) {
            DB::$mysqli->rollback();
            $J->result = false;
        }
        else {
            $J->result = true;
            if (class_exists('Log')) Log::Save(OPERATION::DELETE_VWFLOOR, $fl);
            DB::$mysqli->commit();
        }

        DB::$mysqli->autocommit(TRUE);
        return $J;
    }

    public function changeOrder() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = array();
        $params['id']       = (int)$J->readVar('id',0);
        $params['vw_id']    = (int)$J->readVar('vw_id',0);
        $params['dir']      = $J->readVar('dir');

        if (!in_array($params['dir'], array('left', 'right'))) return $J->error('Неправильный запрос');

        $all = getAllViews_();
        if (!DB::$lastReqState) return $J->error('Не удалось получить список отображений <!--'.DB::getError().'-->');
        $vw = Arr::getValue($all, $params['vw_id'], false);
        if (!is_array($vw)) return $J->error('Отображение не найдено');

        $floors = getFloorsByViewId($params['vw_id']);
        $fl = Arr::getValue($floors['byId'], $params['id'], false);
        if (!$fl) return $J->error('Срез данных не найден');

        $found = false;
        foreach ($floors['byOrder'] as $key=>$f) {
            if (!($f instanceof Floor)) continue;

            if ($f->id == $params['id']) {
                $found = $f;
                $left = Arr::getValue($floors['byOrder'], $key-1, false);
                $right = Arr::getValue($floors['byOrder'], $key+1, false);
                break;
            }
        }

        if ($params['dir'] == 'left' && !$left) return $J->error('Этот элемент уже самый первый');
        if ($params['dir'] == 'right' && !$right) return $J->error('Этот элемент уже самый последний');

        $oldval = $found->view_order;

        if ($params['dir'] == 'left') {
            $found->view_order = $left->view_order;
            //$left->view_order = $oldval;
            $changedId = $left->id;
        }
        else {
            $found->view_order = $right->view_order;
            $changedId = $right->id;
        }

        // transaction start
        DB::$mysqli->autocommit(FALSE);

        $q = "UPDATE `{$this->tablefloors}`
                SET view_order = {$oldval}
                WHERE id = {$changedId}";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
        }

        if ($J->getState()) {
            $q = "UPDATE `{$this->tablefloors}`
                    SET view_order = {$found->view_order}
                    WHERE id = {$found->id}";
            $res = DB::query($q);
            if (!$res || !DB::state()) {
                $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
            }
        }

        if (!$J->getState()) {
            DB::$mysqli->rollback();
            $J->result = false;
        }
        else {
            $J->result = true;
            if (class_exists('Log')) Log::Save(OPERATION::UPDATE_VWFLOOR_ORDER, array('id'=>$found->id, 'old_val'=>$oldval, 'new_val'=>$found->view_order, 'changed_fl'=>$changedId));
            DB::$mysqli->commit();
        }

        DB::$mysqli->autocommit(TRUE);
        return $J;
    }


    public function readFLDSfields (&$J) {
        $params = array();

        $params['action']           = $J->readVar('action');
        $params['id']               = (int)$J->readVar('id',0);
        $params['floor_id']         = (int)$J->readVar('floor_id',0);
        $params['tbl']              = mysql_escape_string($J->readVar('tbl'));
        $params['sen']              = mysql_escape_string($J->readVar('sen'));
        $params['time_min']         = mysql_escape_string($J->readVar('time_min'));
        $params['time_max']         = mysql_escape_string($J->readVar('time_max'));
        $params['time_shift']        = (int)$J->readVar('time_shift',0);
        $params['whatsum']          = mysql_escape_string($J->readVar('whatsum'));
        $params['use_timelimit']    = mysql_escape_string($J->readVar('use_timelimit'));
        return $params;
    }


    public function checkFLDSFields($params) {
        $wrongFields = array();

        $name = 'tbl';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'whatsum';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        return $wrongFields;

    }


    public function updateFLDS() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = $this->readFLDSfields($J);
        $wrongFields = $this->checkFLDSFields($params);

        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }

        //$tablesen

        $q = "SELECT * FROM `{$this->tablesen}` WHERE id = {$params['id']}";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка при проверке данных <!--('.DB::$mysqli->error.')-->');
        }
        $oldval = $res->fetch_assoc();
        if (!is_array($oldval)) return $J->error('Источник данных не существует');

        $q = "UPDATE `{$this->tablesen}`
              SET
                    `tbl` = '{$params['tbl']}',
                    `sen` = '{$params['sen']}',
                    `time_min` = TIME('{$params['time_min']}'),
                    `time_max` = TIME('{$params['time_max']}'),
                    `time_shift` = '{$params['time_shift']}',
                    `whatsum` = '{$params['whatsum']}',
                    `use_timelimit` = '{$params['use_timelimit']}'
              WHERE id = {$params['id']}";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
        }

        $J->result = true;
        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_VWFLDS, array('id'=>$params['id'], 'old_val'=>$oldval, 'new_val'=>$params));
        return $J;
    }




    public function createFLDS($params=null) {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        if (!is_array($params)) {
            $params = $this->readFLDSfields($J);
            $wrongFields = $this->checkFLDSFields($params);

            if (count($wrongFields)) {
                $J->wrongFields = $wrongFields;
                return $J;
            }
        }

        $params = array_merge(array(
            'floor_id'      => 0,
            'tbl'           => 'obj_',
            'sen'           => '',
            'time_min'      => 0,
            'time_max'      => 0,
            'time_shift'    => 0,
            'whatsum'       => '',
            'use_timelimit' => 0
        ), $params);

        $q = "INSERT INTO `{$this->tablesen}`
                    (
                        `id`,
                        `floor_id`,
                        `tbl`,
                        `sen`,
                        `time_min`,
                        `time_max`,
                        `time_shift`,
                        `whatsum`,
                        `use_timelimit`
                    )
              VALUES
                    (
                        NULL,
                        '{$params['floor_id']}',
                        '{$params['tbl']}',
                        '{$params['sen']}',
                        TIME('{$params['time_min']}'),
                        TIME('{$params['time_max']}'),
                        '{$params['time_shift']}',
                        '{$params['whatsum']}',
                        '{$params['use_timelimit']}'
                    )
        ";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
        }

        $J->insertedId = DB::$mysqli->insert_id;
        $params['id'] = $J->insertedId;
        $J->ds = $params;

        if (class_exists('Log')) Log::Save(OPERATION::CREATE_VWFLDS, $params);
        return $J;
    }


    public function deleteFLDS() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = array();
        $params['id']       = (int)$J->readVar('id',0);
        $params['action']   = $J->readVar('action');

        $q = "SELECT * FROM `{$this->tablesen}` WHERE id = {$params['id']}";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            return $J->error('Ошибка при проверке данных <!--('.DB::$mysqli->error.')-->');
        }
        $oldval = $res->fetch_assoc();
        if (!is_array($oldval)) return $J->error('Источник данных не существует');

        $q = "DELETE FROM `{$this->tablesen}` WHERE id = {$params['id']}";
        DB::query($q);
        if (!DB::state()) {
            return $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
        }

        $J->result = true;
        if (class_exists('Log')) Log::Save(OPERATION::DELETE_VWFLDS, $oldval);
        return $J;


    }




    public function getTables() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $J->readVar('action');

        $J->tables = getObjTablesList(getDbTables());
        if (!DB::state()) {
            $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');
        }

        return $J;
    }


    public function getTableFields() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $J->readVar('action');
        $table = mysql_escape_string($J->readVar('table'));

        if (!Arr::getValue($_SESSION, 'tablefields')) $_SESSION['tablefields'] = array();
        $sv = Arr::getValue($_SESSION['tablefields'], $table, false);
        if ($sv) {
            $J->fields = $sv;
            return $J;
        }
        
        $J->fields = getTableFields($table);
        if (!DB::state()) {
            return $J->error('Ошибка получения списка полей таблицы <!--('.DB::$mysqli->error.')-->');
        }
        $_SESSION['tablefields'][$table] = $J->fields;

        return $J;
    }








    public function getSensors() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $J->sensors = array();
        $J->readVar('action');
        $table = mysql_escape_string($J->readVar('table'));

        $tables = getObjTablesList(getDbTables());
        if (!DB::state()) return $J->error('Ошибка при проверке данных <!--('.DB::$mysqli->error.')-->');
        if (!in_array($table, $tables)) return $J->error('Таблица не существует');

        if (!Arr::getValue($_SESSION, 'tablesen')) $_SESSION['tablesen'] = array();
        $sv = Arr::getValue($_SESSION['tablesen'], $table, false);
        if ($sv) {
            $J->sensors = $sv;
            return $J;
        }
        
        $q = "SELECT DISTINCT sen FROM $table ";
        $res = DB::query($q);
        if (!DB::state()) return $J->error('Ошибка при выполнении действия <!--('.DB::$mysqli->error.')-->');


        $sen = array();
        while ($row = $res->fetch_assoc()) {
            $sen[] = Arr::getValue($row, 'sen', '?');
        }

        if (!in_array('manual', $sen)) $sen[] = 'manual';

        $J->sensors = $sen;
        $_SESSION['tablesen'][$table] = $sen;
        return $J;
    }









    public function outPage() {
        ob_start();  /// THE PAGE TEMPLATE BELOW! =============================================================
?>

<form id="convForm" name="convForm" method="POST" action="#" class="well well-large form-inline">
    <fieldset>
        <legend>Конвертация файловых лоадеров в DB-лоадеры</legend>


        <div class="control-group" id="conv-buttons">
            <div  id="convSearchProgress" >
                <p class="help-block">Поиск...</p>
                <div class="progress progress-info" style="height: 5px;" title="0%">
                    <div class="bar" style=" width: 0%;"></div>
                </div>
            </div>

            <div class="span4" style="white-space:nowrap;">
                <button id="btn-conv" class="btn btn-danger" type="button" days="1"><i class="icon-exclamation-sign icon-white"></i> Пересоздать таблицы и запустить процесс конвертации</button>
            </div>


        </div>


    </fieldset>
</form>

<div id="div-convResult"></div>




<script>
    var convObjData = {};
    var cncData = <?php echo json_encode(ConceptionsCollection::allRowsById()); ?>;
    cncData[0] = {id: 0, name: 'Концепция не указана'};
    //var sut = 60 * 60 * 24; //секунд в сутках

    /**
     * Возвращает TS момента времени "текущее время плюс days суток"
     **/
    function getRelTimestamp(days) {
        days = parseInt(days) || 1;

        var ts_sec = Math.round((new Date()).getTime()/1000);
        return ts_sec + sut*days;
    }




    function loadConvObjects(input_params) {
        var params = {
            start_id    : -1,
            action      : '<?php echo self::ACTION; ?>'
        };

        input_params = input_params || {};

        $.extend(params, input_params);



        htmlRequest(
            'converter.php?<?php echo self::ACTION; ?>',
            params,
            function(html) {

                Elm.convResult.append(html);
                /*
                if (!session) {
                    Elm.loginFormModal.dialog('open');
                    Elm.loginFormModal.successCallback = function(){
                        loadConvObjects(input_params);
                    };
                    convButtonsEnable();
                    return;
                }
                */



            },
            function() {
                uiAlert('Ошибка соединения','Error');
                convButtonsEnable();
                convButtonsDefault(Elm.convButtons);
            }

        );

        return;

        ////////////////////////////////////////
        jsonRequest(
                'converter.php?<?php echo self::ACTION; ?>',
                params,

                function(data) {
                    if(!checkSession(data)) {
                        Elm.loginFormModal.dialog('open');
                        Elm.loginFormModal.successCallback = function(){
                            loadConvObjects(input_params);
                        };
                        convButtonsEnable();
                        return;
                    }

                    if (data.hasOwnProperty('relocate') && data.relocate) {
                        window.location.assign(data.relocate);
                    }
                    if (!data.state) {
                        uiAlert(data.message,'Error');
                        Elm.convProgressBar.hide(500);
                        convButtonsEnable();
                        return;
                    }

                    //console.log(data);
                    updateConvProgress(data.response_data.progress);
                    $.extend(ndObjData, data.response_data.ndObjData);

                    var found = data.response_data.found;

                    for (var i in found) {
                        if (!found.hasOwnProperty(i)) continue;
                        var objData = found[i];
                        var oContent = $('#objCell-tmpl').html();
                        var obj = ndObjData[objData.id];
                        obj.thedate = objData.date;

                        for (var prop in obj) {
                            if (!obj.hasOwnProperty(prop)) continue;
                            value = obj[prop]?  obj[prop] : '';
                            oContent = oContent.gReplace('{%'+prop+'%}', value);
                        }

                        var cnccont = getConceptionUL(obj.conception);
                        if (!cnccont) cnccont = Elm.ndUL;
                        cnccont.append(oContent);
                        $('#mon-objCell-'+obj.id+'_'+obj.thedate).show(500);
                    }

                    if (!data.response_data.done) {
                        if (
                                params.start_id == data.response_data.last_id
                                && params.start_time >= data.response_data.last_time
                        ) {
                                //Зацикливание
                                console.log('FIND: infinite cycle on obj_id '+params.start_id + ' - date ' + data.response_data.last_date);
                                params.start_id++;
                                params.start_time = params.from_time;
                        }
                        else {
                            params.start_id = data.response_data.last_id;
                            params.start_time = data.response_data.last_time;
                        }

                        setTimeout(function() {loadConvObjects(params);}, 300);
                    }
                    else setTimeout(function() {
                        hideConvProgress();
                        convButtonsEnable();
                    }, 3000);

                },

                function() {
                    uiAlert('Ошибка соединения','Error');
                    convButtonsEnable();
                    convButtonsDefault(Elm.convButtons);
                }
        );
    }



    function showConvProgress() {
        updateConvProgress(0);
        Elm.convProgressBar.show(200);
    }

    function updateConvProgress(percent) {
        Elm.convProgressLine.css({width: percent*1+'%'});
        Elm.convProgressBar.find('.progress').attr({title: percent*1+'%'});
    }

    function hideConvProgress() {
        Elm.convProgressBar.hide(500);
    }



    function convButtonsDisable() {
        Elm.convButtons.attr({disabled:'disabled'});
    }

    function convButtonsEnable() {
        Elm.convButtons.removeAttr('disabled');
    }

    function convButtonsDefault() {
        Elm.convButtons.attr('class', 'btn btn-danger');
        //btns.find('i.icon').addClass('icon-white');
    }

    function convButtonsActive() {
        Elm.convButtons.attr('class', 'btn btn-warning');
    }


    function response(resp) {
        console.log(resp);

        updateConvProgress(resp.progress);



        if (resp.done || resp.error) {
            hideConvProgress();
            convButtonsDefault();
            convButtonsEnable();
            return;
        }



        var params = {
            start_id    : resp.last_id,
            action      : '<?php echo self::ACTION; ?>'
        };
        setTimeout(function() {loadConvObjects(params);}, 300);

    }





    $(function() {
        Elm.convProgressBar = $('#convSearchProgress').hide();
        Elm.convProgressLine = Elm.convProgressBar.find('.bar');
        Elm.convResult = $('#div-convResult');

        Elm.convButtons = $('#conv-buttons button');

        Elm.convButtons.click(function(){
            Elm.convResult.empty();
            showConvProgress();
            var sthis = $(this);

            convButtonsDefault(Elm.convButtons);
            convButtonsActive(sthis);
            convButtonsDisable();

            loadConvObjects({});
        });




        $('body').css({'overflow-y':'scroll'});
        hideConvProgress();

        /*$('#ul-noData li.noDataCell').click(function() {
            objCellDetails(this);
        });*/
    });

</script>




<?php /// PAGE TEMPLATE ENDS HERE ==================================================================
        $content = ob_get_clean();

        $this->printOut($content);
    }










    public function outView($params) {
        $obj = Arr::getValue($params, 'sourceObj', array());
        $warn = Arr::getValue($params, 'warn', array());
        $label = count($warn)? '<span class="label label-warning">!!!!!!</span>' : '';
        ob_start();  /// THE VIEW TEMPLATE BELOW! ==============================
?>

<div class="well well-small span7" style="padding:5px;">
    <h3 style="color:darkblue;">
        (<?php echo Arr::getValue($obj, 'id', '##'); ?>) - <?php echo Arr::getValue($obj, 'obj_name', '???').' '.$label; ?>
    </h3>
    <div class="span3" style="padding:5px; margin:5px;">
        <strong>Исходный объект</strong>
        <p>&nbsp;</p>
        <?php echo Arr::getValue($params, 'sourceHtml', ''); ?>
    </div>
    <div class="span3" style="padding:5px; margin:5px;">
        <?php echo Arr::getValue($params, 'outHtml', ''); ?>
    </div>
</div>

<script>
$(function() {
    var w = <?php echo json_encode($warn); ?>;
    var id = <?php echo Arr::getValue($obj, 'id', '##'); ?>;
    for (var i in w) {
        if (!w.hasOwnProperty(i)) continue;
        $('#vw-'+id+'-'+i).append('<span class="pull-left">&nbsp;</span><span class="label label-warning pull-left">'+w[i]+'</span>');
    }
});
</script>


<?php /// VIEW TEMPLATE ENDS HERE ==============================================
        $content = ob_get_clean();

        return $content;
    }




    public function outErr($params) {
        $obj = Arr::getValue($params, 'sourceObj', array());
        ob_start();  /// THE ERROR TEMPLATE BELOW! ==============================
?>

<div class="well well-small span7" style="border-color: red; color:red;">
    <h3 style="color:darkblue;">
        (<?php echo Arr::getValue($obj, 'id', '##'); ?>) - <?php echo Arr::getValue($obj, 'obj_name', '???'); ?>
    </h3>
    <?php echo Arr::getValue($params, 'error', ''); ?>
</div>


<?php /// ERROR TEMPLATE ENDS HERE ==============================================
        $content = ob_get_clean();

        return $content;
    }





    public function outFatal($err) {
        ob_start();  /// THE ERROR TEMPLATE BELOW! ==============================
?>

<div class="well well-small span7" style="border-color: red; color:red;">
    <h3 style="color:red;">
        ERROR
    </h3>
    <?php echo $err; ?>
</div>


<?php /// ERROR TEMPLATE ENDS HERE ==============================================
        $content = ob_get_clean();

        return $content;
    }








    public function outJSResponse($params) {

        ob_start();  // ==============================
?>

<script>
    response(<?php echo json_encode($params); ?>);
</script>


<?php /// ============================================
        $content = ob_get_clean();
        return $content;
    }







    public function outConvVwFields($o) {
        if (!$o instanceof loader_data) return;
        $fields = $o->getFields();
        $id = $o->id;
        ob_start();
        foreach ($fields as $field) {
            $val = $o->$field;

// ==============================
?>
<div id="vw-<?php echo $id; ?>-<?php echo $field; ?>"  class="span3" style="font-size:9px;">
    <div class="pull-right" style="max-width:70%;"><?php echo $val; ?></div>
    <div class="pull-left"><?php echo $field; ?></div>
</div>

<?php /// ============================================

}
        $content = ob_get_clean();
        return $content;
    }


    public function outConvFloors($o) {
        if (!$o instanceof loader_data) return;

        $floors = $o->floors;
        $id = $o->id;
        ob_start();
        ?>
<div class="well well-small span">
    <strong> Этажи </strong>
        <?php
        foreach ($floors as $fl) {
            if (!$fl instanceof FL) continue;
            $flid = $fl->id;

// ==============================
?>
    <div id="vw-<?php echo $id; ?>-fl-<?php echo $flid; ?>-name"  class="span3" style="font-size:9px;">
        <hr>
        <div class="pull-right" style="max-width:70%;">(<?php echo $flid; ?>) <?php echo $fl->name; ?></div>
        <div class="pull-left">Название</div>
    </div>

    <div id="vw-<?php echo $id; ?>-fl-<?php echo $flid; ?>-view_order"  class="span3" style="font-size:9px;">
        <div class="pull-right" style="max-width:70%;"><?php echo $fl->view_order; ?></div>
        <div class="pull-left">Порядок отобр.</div>
    </div>
    <div class="well well-small">
        <strong> FLDS </strong>
        <?php
        $dss = $fl->getDs();
        foreach ($dss as $ds) {
            echo '<pre style="font-size:9px;">'.print_r((array)$ds, true).'</pre><hr>';
        }
        ?>
    </div>

<?php /// ============================================




}
        ?>
</div>
        <?php
        $content = ob_get_clean();
        return $content;

    }






    public function printOut( $content = '' ) {

        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm(true);

        $params = array(
            'leftmenu'  => Navbar::getVerticalBar('leftmenu'),//includeFile(APP_PAGE_PARTS.'leftmenu.php'),
            'content'   => $content? $content : ''
        );
        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }












    public function showLogin($cbParams) {
            ?>

<script>
    Elm.loginFormModal.dialog('open');
    Elm.loginFormModal.successCallback = function(){
        loadConvObjects(<?php echo json_encode($cbParams); ?>);
    };
    convButtonsEnable();
</script>


            <?php
    }






    public function processingInOut() {
        timing(); // запуск отсчёта времени процесса
        $maxProcessTime = 5; //секунд на одну итерацию
        $maxObjectsPerIteration = 5; // Прерывать итерацию при большом количестве найденного


        $objects = getAllViews();
        $ids = array_keys($objects);
        sort($ids);
        $total = count($ids);
        $end = $ids[$total-1];


        $skipped = 0;
        $checked = 0;

        $processedObjects = array();

        $action     = Arr::getValue($_REQUEST, 'action', '');
        $start_id   = (int)Arr::getValue($_REQUEST, 'start_id', 0);              // начинать поиск с указанного ид. (текущая часть процесса)

        if ($start_id<0) {
            $this->error = !$this->processingTables();
        }


        $params = array(
            'action'    => $action,
            'start_id'  => $start_id
        );

        if (!Auth::isLogged()) {
            $this->showLogin($params);
            return;
        }


        foreach ($ids as $id) {
            if  ($id < $start_id) {
                $skipped++;
                continue;
            }

            if (timing()>=$maxProcessTime || count($processedObjects)>=$maxObjectsPerIteration || $this->error) {
                break;
            }

            $result = false;
            $obj = Arr::getValue($objects, $id, false);
            if (is_array($obj)) {
                $result = $this->processingView ($obj);
                $this->error = $this->error || !$result;
                if ($result) $processedObjects[] = $id;
                else {
                    break;
                }
            }
            if ($result) $checked++;
            else $skipped++;


        }

        $progress = ceil(($skipped+$checked)*100/$total);
        $done = ($id == $end);
        $params['progress'] = $progress;
        $params['last_id'] = $id;
        $params['processed'] = $processedObjects;
        $params['done'] = $done;
        $params['error'] = $this->error;

        if ($done) {


        ob_start();  // ==============================
?>
<div class="well well-small span7">
    <h3 style="color:green;">Анализ лоадеров завершен успешно</h3>
</div>

<div class="well well-small span7" style="">
    <button id="btn-backup" class="btn btn-danger" type="button" days="1">
        <i class="icon-exclamation-sign icon-white"></i>
        Применить результат конвертации
    </button>
</div>
<script>
$(function() {
    $('#btn-backup').click(function() {
        var params = {
            action      : '<?php echo self::BACKUP_VWTABLE; ?>'
        };



        htmlRequest(
            'converter.php?<?php echo self::BACKUP_VWTABLE; ?>',
            params,
            function(html) {
                Elm.convResult.append(html);
            },
            function() {
                uiAlert('Ошибка соединения','Error');
            }

        );

        return;
    });
});
</script>


<?php /// ============================================
        $content = ob_get_clean();
        $this->resultHtml .= $content;


            $this->resultHtml .= "";
        }

        $this->resultHtml .= $this->outJSResponse($params);


/*
        $params = array(
            'action'    => $action,
            'start_id'  => $start_id
        );
*/
        return $this->resultHtml;


    }

    public function processingView($viewArray) {
        $msg = '';

        $outHtm = '';

        $params = array();
        $warn = array();
        $params['sourceObj'] = $viewArray;
        $id = Arr::getValue($viewArray, 'id', false);

        $loader = $id? getOldLoader($id, $msg) : false;
        if (!$loader || !($loader instanceof main_loader)) {
            $params['error'] = 'Ошибка загрузки лоадера: '.$msg;
            $this->resultHtml .= $this->outErr($params);
            return false;
        }

        $ldata = $loader->getInfo();
        if (!($ldata instanceof loader_data) ) return; // Такого не будет, это для автоподсказок
        if ($ldata->id != $id) {
            $params['error'] = 'ID загруженного лоадера('.$ldata->id.') не совпадает с ожидаемым';
            $this->resultHtml .= $this->outErr($params);
            return false;
        }

        $params['sourceObj'] = (array)$ldata;
        $params['sourceHtml'] = '<pre style="font-size:8px;">'.print_r($ldata, true).'</pre>';
        // @todo обработка объекта

        $o = new loader_data();

        $o->id              = $ldata->id;
        $o->obj_name        = $ldata->obj_name;
        $o->obj_short_name  = $ldata->obj_short_name;
        $o->group           = $ldata->group;
        $o->city_id         = $ldata->city_id;
        $o->obj_type        = $ldata->obj_type + 1;
        $o->view_mode       = 1;
        $o->parent_id       = $ldata->parent_id;
        $o->history_obj_id  = 0;
        $o->view_order      = $ldata->view_order;
        $o->conception      = $ldata->conception;
        $o->pcvideo         = $ldata->pcvideo;
        $o->ivideo          = $ldata->ivideo;
        $o->area            = $ldata->area;
        $o->address         = $ldata->address;
        $o->lattitude       = $ldata->lattitude;
        $o->longitude       = $ldata->longitude;
        $o->dev             = $ldata->dev;
        $o->viewable        = $ldata->viewable;
        $o->logo            = $ldata->logo;
        $o->def_floor       = 0;
        $o->tables          = $ldata->tables;

        $o->time_max        = ((int)$ldata->time_max+1).':00:00';
        $o->time_min        = $ldata->time_min.':00:00';
        $o->use_timelimit   = $ldata->use_timelimit;
        $o->whatsum         = $ldata->whatsum;

        if ($o->parent_id) $o->build_type = 2;
        else {
            if($o->obj_type == 1) $o->build_type = 1;
                else {
                    $o->build_type = 2;
                    $warn['build_type'] = 'Возможно';
                }
        }

        $o->timeshift = str_replace(array(' ', 'INTERVAL', 'HOUR'), '', $ldata->timeshift);
        if ($ldata->timeshift) $warn['timeshift'] = 'Проверить!!';

        if (!is_array($o->tables)||!count($o->tables)) {
            return $this->setErr ('Не указаны таблицы данных.');
        }


        $o->floors = array();


        $view_order = 0;
        $floors = $ldata->floors;
        $df = $ldata->def_floor;

        $allTables = getObjTablesList(getDbTables());

        if (is_array($floors)) {
            foreach ($floors as $code=>$f) {
                if (!($f instanceof TRCfloor)) continue;
                //$code = $f->id;
                $view_order++;

                $fl = new FL();
                $fl->name = $f->name;
                $fl->view_id = $o->id;
                $fl->view_order = $view_order;

                $J = $fl->saveToDB();
                if (!$J->getState()) return $this->setErr ("FL: '$code' - ".$J->getErrorString ());

                $o->floors[] = $fl;
                if ((string)$code == $ldata->def_floor) {
                    $o->def_floor = $fl->id;
                }
                $sen = explode(',',$f->sensors);
                foreach ($sen as $key=>$val) {
                    $l = strlen($val);
                    if ($l && $val[0]=="'" && $val[$l-1]=="'") $sen[$key] = substr($val, 1, $l-2);
                }

                $tables = array();

                foreach ($o->tables as $t) {
                    if (!in_array($t, $allTables)) return $this->setErr("Таблица $t не существует");

                    $ts = array();
                    $fields = getTableFields($t);
                    if (!is_array($fields) || !count($fields))  return $this->setErr("Ошибка при чтении полей таблицы $t");

                    $senIsPresent = false;
                    foreach ($fields as $tf) if (strtolower ($tf) == 'sen') $senIsPresent = true;

                    if ($senIsPresent) {
                        //список датчиков в таблице.
                        $tables[$t] = array();
                        $q = "SELECT DISTINCT sen FROM $t ";
                        $res = DB::query($q);
                        if (!DB::state() || !$res) {
                            return $this->setErr('Ошибка при выполнении действия ('.DB::$mysqli->error.')');
                        }
                        while ($row = $res->fetch_assoc()) {
                            $ts[] = Arr::getValue($row, 'sen', '?');
                        }
                    }


                    $dss = array();
                    foreach ($sen as $s) if (in_array($s, $ts)) $dss[] = $s;
                    $tables[$t]['tablesensors'] = $ts;
                    $tables[$t]['dssensors'] = $dss;

                    /*
                    $dsss = array();
                    foreach ($dss as $sss) $dsss[] = "'$sss'";
*/

                    $ds = new FLDS_();
                    $ds->tbl = $t;
                    $ds->time_max = $o->time_max;
                    $ds->time_min = $o->time_min;
                    $ds->time_shift = $o->timeshift;
                    $ds->use_timelimit = $o->use_timelimit;
                    $ds->whatsum = $o->whatsum;
                    $ds->sen = join(',',$dss);
                    $ds->id = 0;


                    $fl->addDs($ds);
                    $J = $ds->saveToDB();
                    if (!$J->getState()) return $this->setErr ("FLDS: '$t:-$ds->whatsum ({$ds->sen})' - ".$J->getErrorString ());
                }

            }
        }
        else {
            // @todo Warning нет этажей!!
            $warn['floors'] = 'Нет этажей!!';
        }

        $outHtm .= "<strong>Конвертированные поля</strong>".$this->outConvVwFields($o);
        $outHtm .= $this->outConvFloors($o);

        if (!$o->def_floor) {
            $warn['def_floor'] = 'Не определен!!';
        }

        if ($o->id >= 49) {
            $break = 'point';
            //$o->view_mode = 54;
        }

        $J = $this->itemAdd((array)$o);
        if (!$J->getState()) return $this->setErr ("VW: '$o->id:$o->obj_name - ".$J->getErrorString ());

        $params['warn'] = $warn;
        $params['outHtml'] = $outHtm;
        $this->resultHtml .= $this->outView($params);
        return true;
    }










    public function setErr($err) {
        $this->resultHtml .= $this->outFatal($err);
        $this->error = true;
        return false;
    }








    public function processingTables() {

        $vt = new VTABLES();


        $q = "DROP TABLE IF EXISTS `$vt->tablesen`";
        $res = DB::query($q);
        if (!$res || !DB::state()) return $this->setErr ("Ошибка очистки таблицы $vt->tablesen");

        $q = "CREATE TABLE IF NOT EXISTS `$vt->tablesen` (
                `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                `floor_id` int(10) unsigned NOT NULL,
                `tbl` varchar(255) NOT NULL,
                `sen` text,
                `use_timelimit` tinyint(3) unsigned NOT NULL DEFAULT '0',
                `time_min` time NOT NULL,
                `time_max` time NOT NULL,
                `time_shift` int(11) NOT NULL DEFAULT '0',
                `whatsum` varchar(255) NOT NULL,
                PRIMARY KEY (`id`)
              ) ENGINE=InnoDB  DEFAULT CHARSET=utf8";
        $res = DB::query($q);
        if (!$res || !DB::state()) return $this->setErr ("Ошибка создания таблицы $vt->tablesen");








        $q = "DROP TABLE IF EXISTS `$vt->tablefloors`";
        $res = DB::query($q);
        if (!$res || !DB::state()) return $this->setErr ("Ошибка очистки таблицы $vt->tablefloors");

        $q = "CREATE TABLE IF NOT EXISTS `$vt->tablefloors` (
                `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                `name` varchar(255) NOT NULL,
                `view_id` int(10) unsigned NOT NULL,
                `picture` text,
                `view_order` int(11) NOT NULL DEFAULT '1',
                PRIMARY KEY (`id`)
              ) ENGINE=InnoDB  DEFAULT CHARSET=utf8";
        $res = DB::query($q);
        if (!$res || !DB::state()) return $this->setErr ("Ошибка создания таблицы $vt->tablefloors");









        $q = "DROP TABLE IF EXISTS `$vt->tableviews`";
        $res = DB::query($q);
        if (!$res || !DB::state()) return $this->setErr ("Ошибка очистки таблицы $vt->tableviews");


        $q = "CREATE TABLE IF NOT EXISTS `$vt->tableviews` (
                `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                `obj_name` char(96) NOT NULL DEFAULT '',
                `obj_short_name` char(50) NOT NULL,
                `group` int(11) NOT NULL DEFAULT '0',
                `city_id` int(10) unsigned NOT NULL DEFAULT '1',
                `obj_type` tinyint(4) NOT NULL,
                `build_type` int(11) NOT NULL,
                `def_floor` int(11) NOT NULL DEFAULT '0',
                `view_mode` int(11) NOT NULL DEFAULT '1',
                `parent_id` int(10) unsigned NOT NULL,
                `history_obj_id` int(10) unsigned NOT NULL DEFAULT '0',
                `view_order` int(11) NOT NULL DEFAULT '0',
                `conception` bigint(20) unsigned NOT NULL DEFAULT '0',
                `pcvideo` text,
                `ivideo` text,
                `area` int(10) unsigned NOT NULL DEFAULT '0',
                `address` text,
                `lattitude` double NOT NULL DEFAULT '0',
                `longitude` double NOT NULL DEFAULT '0',
                `is_new` char(1) DEFAULT '1',
                `dev` tinyint(4) DEFAULT '1',
                `viewable` char(1) NOT NULL DEFAULT '1',
                `logo` text,
                PRIMARY KEY (`id`),
                KEY `city_id` (`city_id`),
                KEY `viewable` (`viewable`),
                KEY `conception` (`conception`),
                KEY `history_obj_id` (`history_obj_id`)
              ) ENGINE=InnoDB  DEFAULT CHARSET=utf8";
        $res = DB::query($q);
        if (!$res || !DB::state()) return $this->setErr ("Ошибка создания таблицы $vt->tableviews");








        ob_start();  // ==============================
?>
<div class="well well-small span7" style="border-color: blue; color:blue;">
    <h3>Таблицы очищены</h3>
</div>
<?php /// ============================================
        $content = ob_get_clean();
        $this->resultHtml .= $content;
        return true;
    }


    public function renameTables() {
        $vt = new VTABLES();


        $q = "RENAME TABLE `{$vt->tableviews_PRODUCTION}` TO `{$vt->tableviews_PRODUCTION}_backup` ;";
        $res = DB::query($q);
        if (!$res || !DB::state()) return $this->setErr ('Ошибка при выполнении действия ('.DB::$mysqli->error.')');

        $q = "RENAME TABLE `{$vt->tableviews}` TO `{$vt->tableviews_PRODUCTION}` ;";
        $res = DB::query($q);
        if (!$res || !DB::state()) return $this->setErr ('Ошибка при выполнении действия ('.DB::$mysqli->error.')');

        ob_start();  // ==============================
?>
<div class="well well-small span7" style="border-color: green; color:green;">
    <h4>Готово!</h4>
</div>
<?php /// ============================================
        $content = ob_get_clean();
        $this->resultHtml .= $content;
        return true;
    }


    public function processingBackup() {
        $res = $this->renameTables();
        return $this->resultHtml;
    }











}

$page = new Page_converter();

if ($page->action) {
    if ($page->action == Page_converter::ACTION)            echo $page->processingInOut();
    if ($page->action == Page_converter::BACKUP_VWTABLE)    echo $page->processingBackup();








}
else  {
    if (array_key_exists('getList', $_REQUEST)) {
        //if (!Auth::isLogged()) inlineReLocate ('index.php');
        //else $page->itemList();
    }
    else {
        if (!Auth::isLogged()) reLocate ('index.php');

        Navbar::$expanded = 'lm-manage-obj';
        //Navbar::$active = 'list_vw';
        $page->outPage();
    }




}
?>